package util.velocity.impl;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import util.velocity.VelocityTemplateEngine;

import java.io.*;
import java.util.Map;

/**
 * @author Gregory Boissinot
 */
public class VelocityTemplateEngineImpl implements VelocityTemplateEngine {

    @Override
    public String applyTemplate(File templateInputFile, Map<String, Object> params) {
        String content;
        try {

            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateInputFile.getParent());
            velocityEngine.init();

            //-- Make VelocityContext Engine
            VelocityContext velocityContext = new VelocityContext();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                velocityContext.put(entry.getKey(), entry.getValue());
            }

            StringWriter resultWriter = new StringWriter();
            InputStream input = new FileInputStream(templateInputFile);
            if (input == null) {
                throw new RuntimeException("Template file doesn't exist");
            }

            InputStreamReader reader = new InputStreamReader(input, "UTF-8");

            if (!velocityEngine.evaluate(velocityContext, resultWriter, templateInputFile.getName(), reader)) {
                throw new RuntimeException("Failed to convert the template into html.");
            }

            content = resultWriter.toString();

            resultWriter.flush();

            resultWriter.close();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

        return content;
    }
}
